package com.sky.aspect;

import com.sky.anno.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Slf4j
@Aspect
@Component
public class AutoFillAspect {
    @Before("@annotation(com.sky.anno.AutoFill)")
    public void autoFill(JoinPoint joinPoint) {
        log.info("开启公共字段自动填充");
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        AutoFill annotation = signature.getMethod().getAnnotation(AutoFill.class);
        OperationType value = annotation.value();//获取拦截到的方法所用注解的value
        Object[] args = joinPoint.getArgs();
        if (args == null || args.length == 0) return;
        Object arg = args[0];
        Long currentId = BaseContext.getCurrentId();
        LocalDateTime nowTime = LocalDateTime.now();
        try {
            if (value == OperationType.INSERT) {
                Method m1 = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
                Method m2 = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method m3 = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
                Method m4 = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
                m1.invoke(arg, nowTime);
                m2.invoke(arg, nowTime);
                m3.invoke(arg, currentId);
                m4.invoke(arg, currentId);

            } else if (value == OperationType.UPDATE) {
                Method m1 = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method m2 = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
                m1.invoke(arg, nowTime);
                m2.invoke(arg, currentId);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
